package rfid.service;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.nio.charset.StandardCharsets;

import static tools.ByteUtil.hexStringToByteArray;


public class SG_RFID_WriteClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端Active .....");
        ctx.fireChannelActive();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] receiveMsgBytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(receiveMsgBytes);
//        String s1 = printHexString(receiveMsgBytes);
        String var = printHexString(receiveMsgBytes).replace(" ","");
//        String sttt = var.replace("FF1C1180010000", "");

        String sttt = var.substring(14);

//        byte[] b = HexString2Bytes(var);
//        System.out.println(sttt);

        StringBuffer sbResult = new StringBuffer(sttt); //String转换为StringBuffer
        byte[] bytes2 = hexStringToByteArray("0x"+sbResult);

        String st2 = new String(bytes2, StandardCharsets.ISO_8859_1);
//                System.out.println(st);
//                FF 1C 11 80 01 00 00
        if (st2.contains("jÔ")) {
            st2 = st2.replace("jÔ", "-- WRITE OK --");
        }

        System.out.println(Thread.currentThread().getName() + "获取返回的数据:" + st2.substring(1));
//        System.out.println("客户端收到消息: "+ st2.substring(1,512));
//        ctx.fireChannelInactive();
        ctx.close().channel().closeFuture();
    }
 
 
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
 
 
 
    /**
     *  byte数组转16进制字符串
     * @param b
     * @return
     */
    public  String printHexString(byte[] b) {
        StringBuffer sbf = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sbf.append(hex.toUpperCase() + "  ");
        }
        return sbf.toString().trim();
    }
 
 
 
}